
package todolist.logic.task;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.ListIterator;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JOptionPane;

import todolist.entity.TTSEntity;
import todolist.entity.TaskContainerEntity;
import todolist.entity.TaskEntity;
import todolist.util.Utils;

/**
 * Create a Timer object to be invoked when the reminder date is reached, displaying a message showing task name and due date.
 * @author YouLi
 */
public class ReminderController {

	private TaskContainerEntity _entTCE;
	private Timer _tmrReminder;
	private String _strReminderMessage;
	private TaskEntity entRemindingTask;
	private TTSEntity entTTS;
	
	public ReminderController(TaskContainerEntity pobjTCE){
		_entTCE = pobjTCE;
		_tmrReminder = new Timer();
		_strReminderMessage = "";
		entRemindingTask = null;
		entTTS = new TTSEntity("kevin16");
	}
	
	public void setReminder(){
		entRemindingTask = getRemindingTaskEntity();
		if (entRemindingTask != null){
			_strReminderMessage = entRemindingTask.getTaskName() + Utils.getLineSeparator() + "Due On: " + entRemindingTask.getEndDT().getInternalDate();
			_tmrReminder.schedule(new Reminder(), entRemindingTask.getReminderDate());
		}
	}
	
	class Reminder extends TimerTask {
	    public void run() {
	    	entTTS.say("Reminder");
	    	entTTS.say(entRemindingTask.getTaskName());
	    	entTTS.say("Due");
	    	entTTS.say("onnnnnnnnnn");
	    	entTTS.say(entRemindingTask.getEndDT().getInternalDate().toString());
	    	//entTTS.say(_strReminderMessage);
	    	JOptionPane.showMessageDialog(null, _strReminderMessage, "To-Do-List Reminder", JOptionPane.WARNING_MESSAGE, null);
	    	setReminder();
	    }
	}
	
	private TaskEntity getRemindingTaskEntity() {
		GregorianCalendar objGCEarliest = new GregorianCalendar();
		objGCEarliest.add(GregorianCalendar.YEAR, 100);
		ListIterator<TaskEntity> objItr = _entTCE.getListIterator();
		TaskEntity entRemindingTask = null;
		
		while(objItr.hasNext()) {
			TaskEntity entTask = objItr.next();
			Date dtmCurrTask = entTask.getReminderDate();
			if (dtmCurrTask != null) {
				GregorianCalendar objGCCurrTask = new GregorianCalendar();
				objGCCurrTask.setLenient(false);
				objGCCurrTask.setTime(dtmCurrTask);
				if (objGCCurrTask.before(objGCEarliest) && dtmCurrTask.after(new Date()))
					//objGCEarliest = objGCCurrTask;
					entRemindingTask = entTask;
			}
		}
		return entRemindingTask;
	}
	
}
